package com.htgd.gardenexpo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.*;
import com.htgd.gardenexpo.dto.DeviceDTO;
import com.htgd.gardenexpo.dto.GeConDeviceMealDTO;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.page.RecommendQuery;
import com.htgd.gardenexpo.service.DeviceService;
import com.htgd.gardenexpo.service.GeConIntegralGetDetailsService;
import com.htgd.gardenexpo.service.WxUserService;
import com.htgd.gardenexpo.utils.*;
import com.htgd.gardenexpo.utils.HttpRequest;
import com.htgd.gardenexpo.vo.DeviceNumsVO;
import com.htgd.gardenexpo.vo.GeConDeviceMealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: 王秀田
 * @date: 2024/11/19 14:57
 * @description: TODO
 */
@Slf4j
@Service
public class DeviceServiceImpl implements DeviceService {

    @Value("${device.username}")
    private String username;

    @Value("${device.password}")
    private String password;

    @Value("${device.scope}")
    private String scope;

    @Value("${device.grant_type}")
    private String grantType;

    @Value("${device.tenant_id}")
    private String tenantId;

    @Value("${device.authorization}")
    private String authorization;

    @Value("${device.wx_authorization}")
    private String wxAuthorization;

    @Value("${device.login_url}")
    private String loginUrl;

    @Value("${device.device_all_url}")
    private String deviceAllUrl;

    @Value("${device.device_info_url}")
    private String deviceInfoUrl;

    @Value("${device.set_telescope_url}")
    private String setTelescopeUrl;

    @Value("${device.set_charge_time_url}")
    private String setChargeTimeUrl;

    @Value("${device.runway_url}")
    private String runwayUrl;

    @Value("${device.luminousrunway_url}")
    private String luminousrunwayUrl;
    @Value("${device.item_ids}")
    private String itemIds;

    @Value("${device.wx_grant_type}")
    private String wxGrantType;

    @Value("${device.mobile}")
    private String mobile;

    @Value("${wx.public.appId}")
    private String appId;

    @Value("${wx.public.appsecret}")
    private String appsecret;

    @Autowired
    private WeChatUtils weChatUtils;

    @Autowired
    private GeConDeviceMapper geConDeviceMapper;

    @Autowired
    private GeConTelescopeMealMapper geConTelescopeMealMapper;

    @Autowired
    private GeConSeatMealMapper geConSeatMealMapper;

    @Autowired
    private GeConMealOrderMapper geConMealOrderMapper;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private GeConIntegralGetDetailsService geConIntegralGetDetailsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String DELAYED_MESSAGES_ZSET = "delayed:messages";

    @Autowired
    private DelayMessageMapper delayMessageMapper;

    @Autowired
    private WxUserDao wxUserDao;

    @Autowired
    private GeConDeviceStatusMapper geConDeviceStatusMapper;

    @Value("${device.get_telescope_url}")
    private String getTelescopeUrl;

    @Value("${device.get_charge_time_url}")
    private String getChargeTimeUrl;

    /**
     * 设备管理端授权登录
     * @return
     */
    @Override
    public String deviceLogin() throws Exception {
        Map<String,Object> params  = new HashMap<>();
        params.put("scope",scope);
        params.put("grant_type",grantType);
        params.put("username",username);
        params.put("password",password);
        Map<String,Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Tenant-Id",tenantId);
        headers.put("Authorization",authorization);
        String result = HttpRequest.sendHttpPostRequest(loginUrl,params,headers,null);
        if(result!=null&&result!=""){
            JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
            Boolean ok = (Boolean) jsonObject.get("ok");
            if(ok){
                JSONObject data = (JSONObject) jsonObject.get("data");
                JSONObject data1 = (JSONObject) data.get("accessToken");
                return data1.get("tokenValue").toString();
            }
        }
        return null;
    }

    /**
     * 设备小程序授权登录
     * @return
     */
    @Override
    public Map<String,Object> wxLogin(String code, String openId) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", wxGrantType);
        params.put("mobile", mobile + code);
        params.put("code", code);
        params.put("scope", scope);
        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-type", "application/x-www-form-urlencoded");
        headers.put("Tenant-Id", tenantId);
        headers.put("Authorization", wxAuthorization);
        //地址目前先用设备的，测试阶段是这样
        String result = HttpRequest.sendHttpPostRequest(loginUrl,params,headers,"");
        if (result != null && result != "") {
            JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
            System.out.println(JSON.toJSON(jsonObject));
            Boolean ok = (Boolean) jsonObject.get("ok");
            if (ok) {
                Map<String,Object> map = new HashMap<>();
                JSONObject data = (JSONObject) jsonObject.get("data");
                JSONObject data1 = (JSONObject) data.get("accessToken");
                JSONObject data2 = (JSONObject) data.get("additionalParameters");
                String userId = data2.get("userId").toString();
                map.put("tokenValue",data1.get("tokenValue").toString());
                map.put("userId",userId);
                //更新微信用户的甲板id
                wxUserService.updateDeckId(openId,userId);
                return map;
            }
        }
        return null;
    }

    /**
     * 通过第三方接口查询设备列表
     * @return
     */
    @Override
    public CommonResult<JSONArray> getDeviceList() throws Exception {
        CommonResult<JSONArray> result = new CommonResult<>();
        Map<String,Object> params  = new HashMap<>();
        params.put("itemIds",itemIds);
        Map<String,Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Authorization","Bearer "+deviceLogin());
        String str = HttpRequest.sendHttpGetRequest(deviceAllUrl,params,headers);
        if(str!=null&&str!=""){
            JSONObject jsonObject = (JSONObject) JSONObject.parse(str);
            Boolean ok = (Boolean) jsonObject.get("ok");
            if(ok){
                JSONArray data = (JSONArray) jsonObject.get("data");
                for (int i = 0; i < data.size(); i++) { // 通过长度遍历JSONArray
                    // 获取当前元素
                    JSONObject object = data.getJSONObject(i);
                    String deviceId = object.getString("deviceId");
                    String typeId = object.getString("typeId");
                    if(Objects.equals(typeId,"8260")){
                        object.put("typeText","望眼镜");
                    }else if(Objects.equals(typeId,"8261")){
                        object.put("typeText","望眼镜-基础");
                    }else if(Objects.equals(typeId,"8262")){
                        object.put("typeText","望眼镜-照相");
                    }else if(Objects.equals(typeId,"8263")){
                        object.put("typeText","望眼镜-AR");
                    }else if(Objects.equals(typeId,"8140")){
                        object.put("typeText","调温座椅");
                    }else if(Objects.equals(typeId,"100004701")){
                        object.put("typeText","智能座椅");
                    }else{
                        object.put("typeText","其他");
                    }
                    GeConDevice geConDevice = geConDeviceMapper.selectOne(new LambdaQueryWrapper<GeConDevice>().eq(GeConDevice::getDeviceId,deviceId));
                    if(Objects.nonNull(geConDevice)){
                        object.put("uuId",geConDevice.getId());
                    }else{
                        object.put("uuId","");
                    }
                }
                result.setData(data);
                result.setMessage("查询成功");
                result.setCode(200);
                return result;
            }
        }
        result.setData(null);
        result.setMessage("查询失败");
        result.setCode(500);
        return result;
    }

    /**
     * 生成设备二维码
     */
    @Transactional
    @Override
    public ResponseEntity<byte[]> saveDeviceQrCode(String deviceId, String typeId) {
        JSONObject jsonObject = null;
        try {
            jsonObject = getDeviceDetails(deviceId);
        } catch (Exception e) {
            throw new RuntimeException("获取设备详情报错");
        }
        String accessToken = weChatUtils.getAccessToken(appId, appsecret);
        byte[] response = null;
        if(Objects.equals(typeId,"8260")||Objects.equals(typeId,"8261")||Objects.equals(typeId,"8262")||Objects.equals(typeId,"8263")){
            response = weChatUtils.createQRCode(accessToken, "pages/facilService/spyglass",deviceId);
        }
        if(Objects.equals(typeId,"8140")||Objects.equals(typeId,"100004701")){
            response = weChatUtils.createQRCode(accessToken, "pages/facilService/smartSeat",deviceId);
        }
        if(Objects.equals(typeId,"8163")){
            response = weChatUtils.createQRCode(accessToken, "pages/sport/smart-sports/face-registrate",deviceId);
        }
        if(Objects.isNull(response)){
            throw new RuntimeException("生成二维码失败");
        }
        GeConDevice geConDevice1 = geConDeviceMapper.selectOne(new LambdaQueryWrapper<GeConDevice>().eq(GeConDevice::getDeviceId,deviceId));
        if(Objects.nonNull(geConDevice1)){
            geConDevice1.setQrCode(response);
            geConDeviceMapper.updateById(geConDevice1);
        }else{
            GeConDevice geConDevice = new GeConDevice();
            geConDevice.setDeviceId(deviceId);
            geConDevice.setLink("");
            geConDevice.setNum(jsonObject.get("num").toString());
            geConDevice.setCreateTime(LocalDateTime.now());
            geConDevice.setQrCode(response);
            geConDeviceMapper.insert(geConDevice);
        }

        // 设置 HTTP 响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        headers.setContentLength(response.length);
        headers.setContentDispositionFormData("attachment", "QRCode.png");

        return new ResponseEntity<>(response, headers, HttpStatus.OK);

    }

    /**
     * 获取设备详情
     * @return
     */
    @Override
    public JSONObject getDeviceDetails(String deviceId) throws Exception {
        Map<String,Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Authorization","Bearer "+deviceLogin());
        String str = HttpRequest.sendHttpGetRequest(deviceInfoUrl+deviceId,null,headers);
        if(str!=null&& !str.equals("")) {
            JSONObject jsonObject = (JSONObject) JSONObject.parse(str);
            Boolean ok = (Boolean) jsonObject.get("ok");
            if(ok){
                return (JSONObject) jsonObject.get("data");
            }
        }
        return null;
    }

    /**
     * 获取设备二维码
     * @param deviceId
     * @return
     */
    @Override
    public byte[] getQrCode(String deviceId) {
        byte[] bytes = geConDeviceMapper.selectOne(new LambdaQueryWrapper<GeConDevice>().eq(GeConDevice::getDeviceId,deviceId)).getQrCode();
        return bytes;
    }

    /**
     * 查询望眼镜套餐列表
     * @return
     */
    @Override
    public List<GeConTelescopeMeal> getTelescopeMealList() {
        return geConTelescopeMealMapper.selectList(
                new LambdaQueryWrapper<GeConTelescopeMeal>()
                        .eq(GeConTelescopeMeal::getStatus,"0").orderByAsc(true,GeConTelescopeMeal::getId));
    }

    /**
     * 查询座椅套餐列表
     * @return
     */
    @Override
    public List<GeConSeatMeal> getSeatMealList() {
        return geConSeatMealMapper.selectList(
                new LambdaQueryWrapper<GeConSeatMeal>()
                        .eq(GeConSeatMeal::getStatus,"0").orderByAsc(true,GeConSeatMeal::getId));
    }

    /**
     * 确定兑换
     * @param device
     * @param request
     */
    @Transactional
    @Override
    public synchronized CommonResult<JSONObject> deviceSubmit(DeviceDTO device, String openId) throws Exception {
        CommonResult<JSONObject> result = new CommonResult<>();
        JSONObject jsonObject = null;
        try {
            //生成当前状态
            GeConDeviceStatus geConDeviceStatus = geConDeviceStatusMapper.selectById(device.getDeviceId());
            if(geConDeviceStatus==null){
                GeConDeviceStatus entity = new GeConDeviceStatus();
                entity.setDeviceId(device.getDeviceId());
                entity.setStatus("1");
                geConDeviceStatusMapper.insert(entity);
            }else {
                geConDeviceStatusMapper.update(new GeConDeviceStatus(),new LambdaUpdateWrapper<GeConDeviceStatus>()
                        .eq(GeConDeviceStatus::getDeviceId,device.getDeviceId())
                        .set(GeConDeviceStatus::getStatus,"1"));
            }
            //判断当前设备是否正在使用
            boolean exists = geConMealOrderMapper.exists(new LambdaQueryWrapper<GeConMealOrder>().eq(GeConMealOrder::getDeviceId, device.getDeviceId())
                    .eq(GeConMealOrder::getStatus,"0"));
            if(exists){
                return CommonResult.error("该设备正在使用中，请稍后再试！");
            }
            //获取设备详情
            jsonObject = getDeviceDetails(device.getDeviceId());
            String typeId = (String) jsonObject.get("typeId");
            //新建订单
            GeConMealOrder order = new GeConMealOrder();
            Integer integral = 0;
            Integer minute = 0;
            //查询望眼镜套餐
            if(Objects.equals(typeId,"8260")||Objects.equals(typeId,"8261")||Objects.equals(typeId,"8262")||Objects.equals(typeId,"8263")){
                GeConTelescopeMeal geConTelescopeMeal = geConTelescopeMealMapper.selectById(device.getMealId());
                integral = integral + geConTelescopeMeal.getIntegral();
                minute = minute + geConTelescopeMeal.getMinute();
                order.setType("1");
            }
            //查询座椅套餐
            else if(Objects.equals(typeId,"8140")||Objects.equals(typeId,"100004701")){
                GeConSeatMeal geConSeatMeal = geConSeatMealMapper.selectById(device.getMealId());
                integral = integral + geConSeatMeal.getIntegral();
                minute = minute + geConSeatMeal.getMinute();
                order.setType("2");
            } else { //设备类型异常
                result.setCode(500);
                result.setMessage("设备类型不匹配,兑换失败");
                return result;
            }
            //先扣积分
            WxUser user = wxUserService.getOne(new LambdaQueryWrapper<WxUser>().eq(WxUser::getOpenId,openId));
            //判断积分是否充足
            if(user.getIntegralNum()<integral){
                result.setCode(500);
                result.setMessage("您的积分余额不足");
                return result;
            }
            //插入订单数据
            order.setPhone(user.getPhone());
            order.setWxName(user.getName());
            order.setCreateTime(LocalDateTime.now());
            order.setOrderNum(GoodsOrderNoUtils.getIntegralGoodsNum());
            order.setStatus("0");
            order.setOpenId(openId);
            order.setName(jsonObject.get("name").toString());
            order.setTotalIntegral(integral);
            order.setDeviceId(device.getDeviceId());
            order.setMealId(device.getMealId());
            order.setNum(jsonObject.get("num").toString());
            order.setMinute(minute);
            order.setDeviceType(typeId);
            geConMealOrderMapper.insert(order);
            //扣除用户积分
            LambdaUpdateWrapper<WxUser> updateWrapper = new LambdaUpdateWrapper();
            updateWrapper.set(WxUser::getIntegralNum,user.getIntegralNum()-integral);
            updateWrapper.eq(WxUser::getOpenId, openId);
            wxUserService.update(null,updateWrapper);
            //积分消费记录
            GeConIntegralGetDetails geConIntegralGetDetails = new GeConIntegralGetDetails();
            geConIntegralGetDetails.setCreateTime(LocalDateTime.now());
            geConIntegralGetDetails.setGoodsName(jsonObject.get("name").toString());
            geConIntegralGetDetails.setConsumeNum(-Integer.valueOf(integral));
            geConIntegralGetDetails.setAmount(1);
            geConIntegralGetDetails.setOpenId(openId);
            geConIntegralGetDetails.setMethod("积分设备兑换");
            geConIntegralGetDetails.setOrderNum(order.getOrderNum());
            geConIntegralGetDetailsService.save(geConIntegralGetDetails);
            //给望眼镜智能设备充时间
            if(Objects.equals(typeId,"8260")||Objects.equals(typeId,"8261")||Objects.equals(typeId,"8262")||Objects.equals(typeId,"8263")){
                GeConTelescopeMeal telescopeMeal = geConTelescopeMealMapper.selectById(device.getMealId());
                String msg = setTelescopeTime(Integer.valueOf(jsonObject.get("itemId").toString()),
                        Integer.valueOf(jsonObject.get("num").toString()),
                        Integer.valueOf(jsonObject.get("typeId").toString()),
                        telescopeMeal.getMinute()*60);
                if(msg!=null){
                    result.setCode(500);
                    result.setMessage("设备离线,兑换失败");
                    geConMealOrderMapper.deleteById(order.getId());
                    LambdaUpdateWrapper<WxUser> updateWrapper1 = new LambdaUpdateWrapper();
                    updateWrapper1.set(WxUser::getIntegralNum,user.getIntegralNum()+integral);
                    updateWrapper1.eq(WxUser::getOpenId, openId);
                    wxUserService.update(null,updateWrapper1);
                    geConIntegralGetDetailsService.removeById(geConIntegralGetDetails.getId());
                    return result;
                }
            }
            //给座椅智能设备充时间
            if(Objects.equals(typeId,"8140")||Objects.equals(typeId,"100004701")){
                GeConSeatMeal geConSeatMeal = geConSeatMealMapper.selectById(device.getMealId());
                String msg = setSeatTime(Long.valueOf(jsonObject.get("itemId").toString()),
                        Long.valueOf(jsonObject.get("num").toString()),
                        String.valueOf(geConSeatMeal.getMinute()));
                if(msg!=null){//兑换失败
                    result.setCode(500);
                    result.setMessage("设备离线,兑换失败");
                    geConMealOrderMapper.deleteById(order.getId());
                    LambdaUpdateWrapper<WxUser> updateWrapper1 = new LambdaUpdateWrapper();
                    updateWrapper1.set(WxUser::getIntegralNum,user.getIntegralNum()+integral);
                    updateWrapper1.eq(WxUser::getOpenId, openId);
                    wxUserService.update(null,updateWrapper1);
                    geConIntegralGetDetailsService.removeById(geConIntegralGetDetails.getId());
                    return result;
                }
            }
            DelayMessage delayMessage = new DelayMessage();
            delayMessage.setId(UUIDUtils.generateUniqueString());
            delayMessage.setType("3");
            delayMessage.setContent(JSON.toJSONString(order));
            delayMessage.setExpireTime(order.getCreateTime().plusMinutes(order.getMinute()).toEpochSecond(ZoneOffset.of("+8")) * 1000);
            redisTemplate.opsForZSet().add(DELAYED_MESSAGES_ZSET, JSON.toJSONString(delayMessage),
                    order.getCreateTime().plusMinutes(order.getMinute()).toEpochSecond(ZoneOffset.of("+8")) * 1000);
            delayMessageMapper.insert(delayMessage);
            result.setCode(200);
            result.setMessage("兑换成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMessage("兑换失败");
        }
        return result;
    }

    /**
     * 给望眼镜设备充值时间
     * @param itemId 项目ID
     * @param num 设备编号
     * @param deviceType 设备类型ID
     * @param payData 时长（秒）
     * @throws Exception
     */
    @Override
    public String setTelescopeTime(Integer itemId,Integer num,Integer deviceType,Integer payData) throws Exception {
        Map<String,Object> payloadMap  = new HashMap<>();
        payloadMap.put("itemId",itemId);
        payloadMap.put("num",num);
        payloadMap.put("userId",1); //用户id（没有默认1）
        payloadMap.put("deviceType",deviceType);
        payloadMap.put("payData",payData);
        Map<String,Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Tenant-Id",tenantId);
        headers.put("Authorization","Bearer "+deviceLogin());
        log.info("body: {}",payloadMap);
        String result = HttpRequest.sendHttpPostRequest(setTelescopeUrl,
                new HashMap<>(),headers, JSON.toJSONString(payloadMap));
        if(result!=null&&result!=""){
            JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
            log.info("jsonObject: {}",jsonObject);
            Boolean ok = (Boolean) jsonObject.get("ok");
            if(!ok){
                String msg = (String) jsonObject.get("msg");
                return msg;
            }
        }
        return null;
    }

    /**
     * 给座椅设备充值时间
     * @param itemId 项目ID
     * @param num 设备编号
     * @param time 时长（秒）
     * @throws Exception
     */
    @Override
    public String setSeatTime(Long itemId, Long num, String time) throws Exception {
        Map<String,Object > headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Tenant-Id",tenantId);
        headers.put("Authorization","Bearer "+deviceLogin());
        log.info("body: {},{},{}",itemId,num,time);
        String result = HttpRequest.sendHttpGetRequest(setChargeTimeUrl+itemId+"/"+num+"/"+time,null,headers);
        if(result!=null&&result!=""){
            JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
            Boolean ok = (Boolean) jsonObject.get("ok");
            log.info(String.valueOf(jsonObject));
            if(!ok){
                String msg = (String) jsonObject.get("msg");
                return msg;
            }
        }
        return null;
    }

    /**
     * 添加设备套餐
     */
    @Transactional
    @Override
    public void add(GeConDeviceMealDTO geConDeviceMeal) {
        if(Objects.equals(geConDeviceMeal.getType(),"1")){
            GeConTelescopeMeal geConTelescopeMeal = new GeConTelescopeMeal();
            BeanUtils.copyProperties(geConDeviceMeal,geConTelescopeMeal);
            geConTelescopeMeal.setStatus("0");
            geConTelescopeMeal.setCreateTime(LocalDateTime.now());
            geConTelescopeMealMapper.insert(geConTelescopeMeal);
        }else {
            GeConSeatMeal geConSeatMeal = new GeConSeatMeal();
            BeanUtils.copyProperties(geConDeviceMeal,geConSeatMeal);
            geConSeatMeal.setStatus("0");
            geConSeatMeal.setCreateTime(LocalDateTime.now());
            geConSeatMealMapper.insert(geConSeatMeal);
        }
    }

    /**
     * 编辑设备套餐
     */
    @Transactional
    @Override
    public void update(GeConDeviceMealDTO geConDeviceMeal) {
        if(Objects.equals(geConDeviceMeal.getType(),"1")){
            GeConTelescopeMeal geConTelescopeMeal = new GeConTelescopeMeal();
            BeanUtils.copyProperties(geConDeviceMeal,geConTelescopeMeal);
            geConTelescopeMeal.setStatus("0");
            geConTelescopeMeal.setUpdateTime(LocalDateTime.now());
            geConTelescopeMealMapper.updateById(geConTelescopeMeal);
        }
        if(Objects.equals(geConDeviceMeal.getType(),"2")){
            GeConSeatMeal geConSeatMeal = new GeConSeatMeal();
            BeanUtils.copyProperties(geConDeviceMeal,geConSeatMeal);
            geConSeatMeal.setStatus("0");
            geConSeatMeal.setUpdateTime(LocalDateTime.now());
            geConSeatMealMapper.updateById(geConSeatMeal);
        }
    }

    /**
     * 删除设备套餐
     * @param id 套餐ID
     * @param type 设备类型
     */
    @Transactional
    @Override
    public void delete(String id,String type){
        if(Objects.equals(type,"1")){
            GeConTelescopeMeal geConTelescopeMeal = new GeConTelescopeMeal();
            geConTelescopeMeal.setId(id);
            geConTelescopeMeal.setStatus("1");
            geConTelescopeMeal.setDeleteTime(LocalDateTime.now());
            geConTelescopeMealMapper.updateById(geConTelescopeMeal);
        }
        if(Objects.equals(type,"2")){
            GeConSeatMeal geConSeatMeal = new GeConSeatMeal();
            geConSeatMeal.setId(id);
            geConSeatMeal.setStatus("1");
            geConSeatMeal.setDeleteTime(LocalDateTime.now());
            geConSeatMealMapper.updateById(geConSeatMeal);
        }
    }

    @Override
    public PageInfo<GeConDeviceMealVO> pageList(RecommendQuery pageBase){
        PageHelper.startPage(pageBase.getPageNum(), pageBase.getPageSize());
        List<GeConDeviceMealVO> list = geConDeviceMapper.pageList(pageBase);
        list.stream().forEach(item->{
            if(Objects.equals(item.getType(),"1")){
                item.setTypeText("望眼镜");
            }else{
                item.setTypeText("座椅");
            }
        });
        return new PageInfo<>(list);
    }

    @Override
    public CommonResult getUseNums(String startTime, String endTime, String deviceType, String deviceCode){
        //全部数据
        if(deviceType==null && deviceCode==null){
            DeviceNumsVO deviceNumsVO = new DeviceNumsVO();
            String token = "";

            try {
                token = deviceLogin();
            } catch (Exception e) {
                log.info("综管-获取各种设备-授权登录-报错：{}",e.toString());
            }

            //望远镜和座椅使用人次
            Long telescopeUseNums = geConMealOrderMapper.getNumsByType("1",startTime,endTime, deviceCode);
            Long seatUseNums = geConMealOrderMapper.getNumsByType("2", startTime, endTime, deviceCode);
            deviceNumsVO.setTelescopeUseNums(telescopeUseNums);
            deviceNumsVO.setSeatUseNums(seatUseNums);

            //导览注册人数
            Long faceNums = wxUserDao.getFaceNums(startTime,endTime);
            deviceNumsVO.setGuideAddNums(faceNums);

            //打卡杆打卡人数
            String url1 = runwayUrl;
            String urlWithParams = UriComponentsBuilder.fromHttpUrl(url1)
                    .queryParam("itemId", Long.valueOf(itemIds))  // 添加 itemId 参数
                    .queryParam("startTime", startTime)  // 添加 startTime 参数
                    .queryParam("endTime", endTime)  // 添加 endTime 参数
                    .toUriString();  // 将 URL 转换成字符串
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set(HttpHeaders.AUTHORIZATION, "Bearer "+token);
            headers.set("Tenant-Id", tenantId);


            HttpEntity<String> request = new HttpEntity<>(headers);

            RestTemplate restTemplate1 = new RestTemplate();

            // 发送请求
            ResponseEntity<String> response1 = restTemplate1.exchange(urlWithParams, HttpMethod.GET, request, String.class);
            String responseBody1 = response1.getBody();
            JSONObject jsonObject1 = JSONObject.parseObject(responseBody1);
            if(jsonObject1!=null && jsonObject1.getInteger("code")==0){
                String data = jsonObject1.getString("data");
                deviceNumsVO.setPoleUseNums(Long.parseLong(data));
            }else {
                return CommonResult.error("获取打卡杆打卡人数失败："+responseBody1);
            }


            //追光跑道
            String url2 = luminousrunwayUrl;
            String urlWithParams2 = UriComponentsBuilder.fromHttpUrl(url2)
                    .queryParam("itemId", Long.valueOf(itemIds))  // 添加 itemId 参数
                    .queryParam("startTime", startTime)  // 添加 startTime 参数
                    .queryParam("endTime", endTime)  // 添加 endTime 参数
                    .toUriString();  // 将 URL 转换成字符串

            RestTemplate restTemplate2 = new RestTemplate();

            // 发送请求
            ResponseEntity<String> response2 = restTemplate2.exchange(urlWithParams2, HttpMethod.GET, request, String.class);
            String responseBody2 = response2.getBody();
            JSONObject jsonObject2 = JSONObject.parseObject(responseBody2);
            if(jsonObject2.getInteger("code")==0){
                String data = jsonObject2.getString("data");
                deviceNumsVO.setRunwayUseNums(Long.parseLong(data));
            }else {
                return CommonResult.error("获取追光跑道使用人数失败："+responseBody2);
            }

            return CommonResult.success("查询成功",deviceNumsVO);
        }
        if (deviceType!=null && deviceCode==null && !"".equals(deviceType)){//只传类型
            Map<String,Long> map = new HashMap<>();
            switch (deviceType){
                case "8140":
                    Long seatUseNums = geConMealOrderMapper.getNumsByType("2", startTime, endTime, deviceCode);
                    map.put("seatUseNums",seatUseNums);
                    break;
                case "8163":
                    map.put("poleUseNums",0L);
                    break;
                case "8232":
                    map.put("guideAddNums",0L);
                    break;
                case "8263":
                    Long telescopeUseNums = geConMealOrderMapper.getNumsByType("1",startTime,endTime, deviceCode);
                    map.put("telescopeUseNums",telescopeUseNums);
                    break;
                case "8191":
                    map.put("runwayUseNums",0L);
                    break;
                default:
                    break;
            }
            return CommonResult.success("查询成功",map);
        }

        if(!"".equals(deviceCode) && deviceType!=null && !"".equals(deviceType)){//都传
            Map<String,Long> map = new HashMap<>();
            switch (deviceType){
                case "8140":
                    Long seatUseNums = geConMealOrderMapper.getNumsByType("2", startTime, endTime,deviceCode);
                    map.put("seatUseNums",seatUseNums);
                    break;
                case "8163":
                    map.put("poleUseNums",0L);
                    break;
                case "8232":
                    map.put("guideAddNums",0L);
                    break;
                case "8263":
                    Long telescopeUseNums = geConMealOrderMapper.getNumsByType("1",startTime,endTime,deviceCode);
                    map.put("telescopeUseNums",telescopeUseNums);
                    break;
                case "8191":
                    map.put("runwayUseNums",0L);
                    break;
                default:
                    break;
            }
            return CommonResult.success("查询成功",map);

        }

        return CommonResult.success("查询成功");
    }

    @Override
    public CommonResult closeDevice(String deviceId, String type) {
        if(deviceId==null){
            return CommonResult.error("请传入设备id");
        } if(type==null){
            return CommonResult.error("缺少类型参数");
        }
        if("1".equals(type)){ //正常结束
            try {
                GeConMealOrder geConMealOrder = geConMealOrderMapper.selectOne(new LambdaQueryWrapper<GeConMealOrder>().eq(GeConMealOrder::getDeviceId, deviceId)
                        .eq(GeConMealOrder::getStatus, "0"));

                if(geConMealOrder==null){
                    return CommonResult.error("无正在使用的该设备订单");
                }else {
                    geConMealOrderMapper.update(new GeConMealOrder(), new LambdaUpdateWrapper<GeConMealOrder>().eq(GeConMealOrder::getDeviceId, deviceId)
                            .set(GeConMealOrder::getStatus, "1"));
                    return CommonResult.success("关闭成功");
                }
            }catch (Exception e){
                System.out.println(e);
                return CommonResult.error("获取正在进行的设备失败");
            }
        }else {
            try {
                GeConMealOrder geConMealOrder = geConMealOrderMapper.selectOne(new LambdaQueryWrapper<GeConMealOrder>().eq(GeConMealOrder::getDeviceId, deviceId)
                        .eq(GeConMealOrder::getStatus, "0"));

                if(geConMealOrder==null){
                    return CommonResult.error("无正在使用的该设备订单");
                }else {
                    geConDeviceStatusMapper.update(new GeConDeviceStatus(), new LambdaUpdateWrapper<GeConDeviceStatus>().
                            eq(GeConDeviceStatus::getDeviceId, deviceId)
                            .set(GeConDeviceStatus::getStatus, type));

                    geConMealOrderMapper.update(new GeConMealOrder(), new LambdaUpdateWrapper<GeConMealOrder>().eq(GeConMealOrder::getDeviceId, deviceId)
                            .set(GeConMealOrder::getStatus, "1"));
                    return CommonResult.success("关闭成功");
                }
            }catch (Exception e){
                System.out.println(e);
                return CommonResult.error("获取正在进行的设备失败");
            }

        }



    }

    @Override
    public CommonResult getTelescopeRemainingTime(String num) {
        Map<String,Object> params  = new HashMap<>();
        params.put("itemId",Integer.valueOf(itemIds));
        params.put("num",Integer.valueOf(num));
        params.put("userId",1);
        params.put("deviceType",8263);
        Map<String,Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Tenant-Id",tenantId);
        String result = null;
        try {
            result = HttpRequest.sendHttpGetRequest(getTelescopeUrl,params,headers);
            if(result!=null&& !result.equals("")){
                JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
                Boolean ok = (Boolean) jsonObject.get("ok");
                if(ok){
                    String time = (String) jsonObject.get("data");
                    return CommonResult.success("查询成功",time);
                }else {
                    return CommonResult.error("获取剩余时间失败："+result);

                }
            }else {
                return CommonResult.error("获取剩余时间失败： "+result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error("获取剩余时间失败："+e);
        }
    }

    @Override
    public CommonResult getSeatRemainingTime(String num) {
        Map<String,Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Tenant-Id",tenantId);
        String result = null;
        try {
            result = HttpRequest.sendHttpGetRequest(getChargeTimeUrl+Long.valueOf(itemIds)+"/"+Long.valueOf(num),null,headers);
            if(result!=null&& !result.equals("")){
                JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
                Boolean ok = (Boolean) jsonObject.get("ok");
                if(ok){
                    String time = (String) jsonObject.get("data");
                    return CommonResult.success("查询成功",time);
                }else {
                    return CommonResult.error("获取剩余时间失败："+result);

                }
            }else {
                return CommonResult.error("获取剩余时间失败： "+result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error("获取剩余时间失败："+e);
        }
    }

}
